<template>
  <div class="h-full">
    <div class="bg-white h-full rounded-[2px] overflow-hidden px-[16px]">
      <vxe-toolbar ref="toolbarRef">
        <template #tools>
          <el-button
            type="primary"
            class="my-[0.5em]"
            @click="toolbarButtonEvent({ code: ACTION_TYPE.TADD })"
            >{{ t("store_group.form.add") }}
          </el-button>
          <!--          <el-button-->
          <!--            type="primary"-->
          <!--            plain-->
          <!--            @click="toolbarButtonEvent({ code: toolbarButtons[1].code })"-->
          <!--            >{{ toolbarButtons[1].name }}-->
          <!--          </el-button>-->
          <el-button type="primary" plain @click="getGroupTableList"
            >{{ t("store_group.form.refresh") }}
          </el-button>
        </template>
      </vxe-toolbar>

      <vxe-table
        ref="tableRef"
        border="inner"
        class="group-table"
        :column-config="{ resizable: false }"
        :row-config="{ isHover: true, keyField: 'id' }"
        :loading="loading"
        :tree-config="{
          rowField: 'id',
          childrenField: 'children',
          iconOpen: 'iconfont icon-zhankai',
          iconClose: 'iconfont icon-zhedie',
          accordion: true,
          expandRowKeys: ['0']
        }"
        :expand-config="expandConfig"
        :data="tableData"
        @toggle-tree-expand="toggleExpandChangeEvent"
      >
        <vxe-column
          :title="t('store_group.form.group_name')"
          align="left"
          field="name"
          width="300"
          tree-node
        >
          <template #default="{ row }">
            <span class="cursor-pointer relative">
              <i
                :class="[
                  'iconfont text-[--autata-font-gray-color]',
                  row.expand ? 'icon-zhankai' : 'icon-zhedie',
                  row.type === 'store' && row.device_num > 0 ? '' : 'invisible'
                ]"
                @click="expand(row)"
              />
              <span class="inline-block pl-[40px]" @click="expand(row)">{{
                row.name
              }}</span>
              <el-tag
                v-if="row.type === 'store'"
                :type="row.store_status ? 'info' : 'success'"
                class="absolute"
                :style="{ left: `${getByteLength(row.name) + 80}px` }"
                >{{
                  row.store_status
                    ? t("store_group.form.closed")
                    : t("store_group.form.operating")
                }}
              </el-tag>
            </span>
          </template>
        </vxe-column>
        <vxe-column type="expand" title="" width="10">
          <template #content="{ row }">
            <div class="wrap">
              <div
                v-for="item in row.deviceList"
                :key="item.id"
                class="flex items-center border-b-[--autata-line-color] border-b-[1px] last:border-b-0"
                :style="{ paddingLeft: `${(row.level + 2) * 20 + 40}px` }"
              >
                <div>{{ item.device_id }}</div>
                <div class="py-[10px] ml-[40px]">
                  <el-tag :type="formatStatusText(item).status"
                    >{{ formatStatusText(item).text }}
                  </el-tag>
                </div>
                <div class="ml-[40px]">
                  {{ item.activation_time }}
                </div>
              </div>
            </div>
          </template>
        </vxe-column>
        <vxe-column
          :title="t('store_group.form.description')"
          align="center"
          field="info"
        />
        <vxe-column
          :title="t('store_group.form.store_num')"
          align="center"
          :width="100"
          field="store_num"
        />
        <vxe-column
          :title="t('store_group.form.device_num')"
          align="center"
          :width="100"
          field="device_num"
        />
        <!--      <vxe-column title="分组图标" align="center" field="icon" />-->
        <vxe-column
          :title="t('store_group.form.create_time')"
          align="center"
          field="create_time"
          :width="190"
        />
        <vxe-column
          :title="t('store_group.form.operation')"
          :width="240"
          align="center"
        >
          <template #default="{ row }">
            <div v-if="row.type !== 'store'">
              <!--              <el-button-->
              <!--                link-->
              <!--                type="primary"-->
              <!--                @click="actionClick(ACTION_TYPE.VIEW, row)"-->
              <!--              >-->
              <!--                查看-->
              <!--              </el-button>-->
              <!--              <el-divider direction="vertical" />-->
              <el-button
                link
                type="primary"
                @click="actionClick(ACTION_TYPE.ADD, row)"
              >
                {{ t("store_group.form.add_sub_group") }}
              </el-button>
              <el-divider direction="vertical" />
              <el-button
                link
                type="primary"
                @click="actionClick(ACTION_TYPE.EDIT, row)"
              >
                {{ t("store_group.form.edit_group") }}
              </el-button>
              <el-divider direction="vertical" />
              <el-button
                link
                type="primary"
                @click="actionClick(ACTION_TYPE.DELETE, row)"
              >
                {{ t("store_group.form.delete_group") }}
              </el-button>
            </div>
          </template>
        </vxe-column>
      </vxe-table>
    </div>

    <group-modal
      v-model="showGroupPopup"
      :action-type="actionType"
      :formData="formData"
      @submit="handleGroupForm"
    />
  </div>
</template>

<script lang="ts" setup>
import { getCurrentInstance, nextTick, onMounted, ref } from "vue";
import {
  VxeTableInstance,
  VxeTableEvents,
  VxeToolbarPropTypes,
  VxeToolbarInstance,
  VxeTablePropTypes
} from "vxe-table";
import {
  addStoreGroup,
  delStoreGroup,
  getGroupList,
  getStoreList,
  GroupProp,
  uptStoreGroup
} from "@/api/teaInfuser/store";
import { ACTION_TYPE } from "@/components/AuTable/type";
import { ElMessage, ElMessageBox } from "element-plus";
import { useDetail } from "./hooks";
import { pick } from "lodash-unified";
import { BaseProps } from "@/components/AuForm/type";
import { getReleaseSelect } from "@/api/teaInfuser/formula";
import GroupModal from "@/views/teaInfuser/store/storeGroup/groupModal.vue";
import { deviceGetList, DeviceProp } from "@/api/teaInfuser/device";
import { useI18n } from "vue-i18n";

const tableRef = ref<VxeTableInstance<GroupProp>>();
const toolbarRef = ref<VxeToolbarInstance>();
const formRef = ref();

const { t } = useI18n();
const { toDetail } = useDetail();
const { proxy } = getCurrentInstance();

const loading = ref(false);
const expandConfig = ref<VxeTablePropTypes.ExpandConfig<GroupProp>>({
  visibleMethod({ row }) {
    if (row.type === "store") {
      return false;
    }
    return false;
  },
  toggleMethod({ expanded, row }) {
    if (expanded) {
      if (row.type !== "store") {
        return false;
      }
      if (row.device_num <= 0) {
        return false;
      }
    }
    return true;
  }
});
const tableData = ref<GroupProp[]>([]);
let expandList = [];
const rowData = ref<Partial<GroupProp>>({});
const toolbarButtons = ref<VxeToolbarPropTypes.Buttons>([
  { code: ACTION_TYPE.TADD, name: "新增" },
  { code: "expand", name: "展开" }
]);

const showGroupPopup = ref(false);
const formList = ref<BaseProps[]>([
  {
    type: "el-tree-select",
    key: "parent_id",
    label: "store_group.form.group",
    placeholder: "store_group.form.select_group",
    checkStrictly: true,
    renderAfterExpand: false,
    disabled: false,
    props: {
      value: "id",
      label: "name"
    },
    required: true,
    data: []
  },
  {
    type: "el-input",
    key: "name",
    label: "store_group.form.group_name",
    placeholder: "store_group.form.enter_group_name",
    required: true
  },
  {
    type: "el-input",
    key: "info",
    label: "store_group.form.description",
    placeholder: "store_group.form.enter_description"
  }
]);
const formData = ref<Partial<GroupProp>>({});
const actionType = ref(ACTION_TYPE.TADD);

const toggleExpandChangeEvent: VxeTableEvents.ToggleTreeExpand = params => {
  const $table = tableRef.value;
  if ($table) {
    const { row, expanded } = params;
    console.log(
      "节点展开事件",
      expanded,
      "获取父节点：",
      $table.getParentRow(row)
    );
  }
};

const handleTreeNum = (tree: any[]) => {
  function traverse(node: {
    store_list: any[];
    children: any[];
    store_num: number;
    device_num: number;
    type: string;
    level: number;
  }) {
    let storeNum = 0;
    let deviceNum = 0;
    let level = node.level ? node.level + 1 : 1;

    // 如果当前节点有store_list，累加长度
    if (node.store_list) {
      storeNum += node.store_list.length;
      deviceNum += node.store_list.reduce(
        (acc, cur) => acc + (cur?.device_list?.length ?? 0),
        0
      );
      for (const store of node.store_list) {
        if (!node.children.find(item => item.id === store.id)) {
          node.children.unshift({
            id: store.id,
            name: store.name,
            type: "store",
            expand: false,
            device_num: store.device_list?.length ?? 0,
            deviceList: store.device_list,
            store_status: store.store_status,
            level: node.level ? node.level + 1 : 2
          });
        }
      }
    }

    if (node.type === "store") {
      deviceNum = node.device_num;
    }

    // 递归处理子节点
    if (node.children && node.children.length > 0) {
      node.children.forEach(child => {
        if (child.type !== "store") {
          storeNum += traverse(child).storeNum;
          deviceNum += traverse(child).deviceNum;
        }
        level = traverse(child).level;
      });
    }

    // 添加store_num字段
    node.store_num = storeNum;
    node.device_num = deviceNum;
    node.level = level;

    return { storeNum, deviceNum, level };
  }

  // 遍历树结构
  tree.forEach(traverse);

  return tree;
};

const getGroupTableList = async () => {
  loading.value = true;
  try {
    const res = await getReleaseSelect({});
    const resStore = await getStoreList({});
    const filterZero = resStore.data.filter(item => item.group_id == 0);

    const list = [];
    for (const store of filterZero) {
      const device = await deviceGetList({ store_id: store.id });
      list.push({
        id: store.id,
        name: store.name,
        device_num: store.device_num,
        device_list: device.data,
        store_status: store.store_status
      });
    }
    const china = [
      {
        id: "0",
        name: "全国",
        children: res.data,
        store_list: list
      }
    ];
    tableData.value = handleTreeNum(china);
    console.log(tableData.value);
    loading.value = false;
    // await nextTick(() => {
    //   expandAllEvent();
    // });
  } catch (e) {
    console.error(e);
    tableData.value = [];
    loading.value = false;
  }
  // await tableRef.value.setTreeExpand(expandList, true);
};

const expandAllEvent = () => {
  const $table = tableRef.value;
  if ($table) {
    $table.setAllTreeExpand(true);
    $table.setAllRowExpand(true);
    toolbarButtons.value[1] = {
      code: "closeExpand",
      name: t("store_group.form.collapse")
    };
  }
};

const closeExpandEvent = () => {
  const $table = tableRef.value;
  if ($table) {
    $table.clearTreeExpand();
    $table.clearRowExpand();
    toolbarButtons.value[1] = {
      code: "expand",
      name: t("store_group.form.expand")
    };
  }
};

const expand = (row: GroupProp) => {
  const $table = tableRef.value;
  if ($table) {
    row.expand = !row.expand;
    if (row.type === "store") {
      $table.setRowExpand(row, row.expand);
    } else {
      $table.setTreeExpand(row, row.expand);
    }
  }
};
type status = "success" | "warning" | "info" | "primary" | "danger";

function getByteLength(str) {
  const cw = 16; // 假设中文字符宽度为16px
  const ew = 8; // 假设英文字符宽度为8px
  let totalWidth = 0;
  for (let i = 0; i < str.length; i++) {
    const charCode = str.charCodeAt(i);
    // 中文字符范围
    if (charCode >= 0x4e00 && charCode <= 0x9fff) {
      totalWidth += cw;
    } else {
      // 英文字符和数字
      totalWidth += ew;
    }
  }
  return totalWidth;
}

function formatStatusText(row: DeviceProp): {
  text: string;
  status: status;
} {
  let text = "",
    status: status = "success";
  if (row.device_status === 0 && row.store_id != null) {
    text = t("store_group.form.normal");
    status = "primary";
  } else if (row.store_id === null) {
    text = t("store_group.form.not_activated");
    status = "info";
  } else if (row.device_status === 1) {
    text = t("store_group.form.locked");
    status = "danger";
  }
  return {
    text,
    status
  };
}

const addShowModal = async () => {
  showGroupPopup.value = true;
};

const toolbarButtonEvent = async ({ code }: { code: ACTION_TYPE | string }) => {
  switch (code) {
    case ACTION_TYPE.TADD:
      actionType.value = code;
      await addShowModal();
      formData.value = {
        parent_id: 0,
        info: "",
        name: ""
      };
      break;
    case "closeExpand":
      closeExpandEvent();
      break;
    case "expand":
      expandAllEvent();
      break;
  }
};

const handleGroupForm = (data: GroupProp) => {
  let service = addStoreGroup;
  if (data.id) {
    if (data.parent_id === rowData.value.id) {
      ElMessage({
        message: t("store_group.form.group_cannot_same_parent"),
        type: "warning"
      });
      return;
    }
    service = uptStoreGroup;
  }
  service(data).then(res => {
    ElMessage({
      message: data.id
        ? t("store_group.form.edit_success")
        : t("store_group.form.add_success"),
      type: "success"
    });
    showGroupPopup.value = false;

    expandList = tableRef.value.getTreeExpandRecords();
    getGroupTableList();
  });
};

const actionClick = async (type: ACTION_TYPE, row: Partial<GroupProp>) => {
  rowData.value = row;
  actionType.value = type;
  switch (type) {
    case ACTION_TYPE.ADD:
      formData.value = {
        parent_id: row.id
      };
      await addShowModal();
      await formRef.value.setFormProps("parent_id", { disabled: true });
      break;
    case ACTION_TYPE.VIEW:
      toDetail(pick(row, ["id", "name"]) as {}, "query");
      break;
    case ACTION_TYPE.EDIT:
      formData.value = row;
      await addShowModal();
      await formRef.value.setFormProps("parent_id", { disabled: true });
      break;
    case ACTION_TYPE.DELETE:
      proxy.$auMessageBox
        .confirm(
          t("store_group.form.delete_confirm", { name: row.name }),
          t("store_group.form.tip"),
          {
            type: "error"
          }
        )
        .then(async () => {
          const res = await delStoreGroup({
            delList: JSON.stringify([{ id: row.id }])
          });
          if (res.code === 200) {
            ElMessage({
              message: t("notice.delete_success"),
              type: "success"
            });
            await getGroupTableList();
          }
        })
        .catch(() => {});
      break;
  }
};

onMounted(() => {
  getGroupTableList();

  const $table = tableRef.value;
  const $toolbar = toolbarRef.value;
  if ($table && $toolbar) {
    $table.connect($toolbar);
  }

  for (const item of formList.value) {
    item.style = {
      width: "200px"
    };
  }
});
</script>

<style lang="scss" scoped>
.group-table {
  :deep(.vxe-tree--node-btn.iconfont) {
    color: var(--autata-font-gray-color);
    transform: translateY(-20%);
  }

  :deep(.vxe-body--expanded-cell) {
    padding: 0 !important;
    background: var(--autata-striped-bg-color);
  }
}
</style>
